package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import kong.unirest.*;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Liang Jianlin
 * @date 2024-04-30 02:28
 */
public class DataSourceController {
    @FXML
    public VBox sourceContainer;
    @FXML
    public Button upLoad;
    @FXML
    public Button choose;
    @FXML
    public VBox uploadContainer;
    @FXML
    public Label chosenFileName;
    @FXML
    public ComboBox typeComboBox;
    public RadioButton pptButton;
    public RadioButton documentButton;
    public RadioButton videoButton;
    private String courseID;
    File selectedFile;
    Map <String,JSONArray> sortMap = new HashMap<>();
    JSONArray docArr = new JSONArray();
    JSONArray pptArr = new JSONArray();
    JSONArray vidArr = new JSONArray();
    private Map<String,String> typeMap = new HashMap<>();
    public void initialize(){
        typeMap.put("文档","document");
        typeMap.put("课件","ppt");
        typeMap.put("视频","video");
        if(!Objects.equals(Globalvar.userRole, "ADMIN")){
            uploadContainer.setVisible(false);
            uploadContainer.setManaged(false);
        }
//        documentButton.selectedProperty().addListener((observable, oldValue, newValue) -> {
//            System.out.println("12345");
//            if (newValue) {
//                for (int i = 0; i < docArr.length(); i++) {
//                    sourceContainer.getChildren().add((Node) docArr.get(i));
//                }
//            }else{
//                for (int i = 0; i < docArr.length(); i++) {
//                    sourceContainer.getChildren().remove((Node) docArr.get(i));
//                }
//            }
//        });
//
//        pptButton.selectedProperty().addListener((observable, oldValue, newValue) -> {
//            if (newValue) {
//                for (int i = 0; i < pptArr.length(); i++) {
//                    sourceContainer.getChildren().add((Node) pptArr.get(i));
//                }
//            }else{
//                for (int i = 0; i < pptArr.length(); i++) {
//                    sourceContainer.getChildren().remove((Node) pptArr.get(i));
//                }
//            }
//        });
//
//        videoButton.selectedProperty().addListener((observable, oldValue, newValue) -> {
//            if (newValue) {
//                for (int i = 0; i < vidArr.length(); i++) {
//                    sourceContainer.getChildren().add((Node) vidArr.get(i));
//                }
//            }else{
//                for (int i = 0; i < vidArr.length(); i++) {
//                    sourceContainer.getChildren().remove((Node) vidArr.get(i));
//                }
//            }
//        });

        //选择文件
        ObservableList<String> typeItem = FXCollections.observableArrayList("文档","课件","视频");
        typeComboBox.setItems(typeItem);
        choose.setOnAction(e->{
            FileChooser fileChooser = new FileChooser();
            selectedFile = fileChooser.showOpenDialog(null); // null表示使用默认的所有者窗口
            if (selectedFile != null) {
                // 用户选择了一个文件，你可以在这里处理它
                System.out.println("选定的文件是: " + selectedFile.getAbsolutePath());
                // ... 你可以将文件路径保存到某个变量中，或者执行其他操作 ...
                chosenFileName.setText(selectedFile.getAbsolutePath());
            }
        });


        upLoad.setOnAction(e->{
            System.out.println(selectedFile);
            System.out.println(typeMap.get(typeComboBox.getValue()));
            System.out.println(courseID);

            HttpResponse<Empty> res = HttpUtil.post(Globalvar.baseUrl+"/api/resources/course")
                    .header("content-type", "multipart/form-data")
                    .field("type", typeMap.get(typeComboBox.getValue()))
                    .field("courseId", courseID)
                    .field("file", new File(String.valueOf(selectedFile)))
                    .asEmpty();
            System.out.println(res.getStatus());
            if(res.getStatus() == 404){
                chosenFileName.setText("上传失败");
            }else if(res.getStatus() == 200){
                chosenFileName.setText("上传成功");
            }
        });
    }
    public void setSource(String id) throws IOException {
        courseID = id;
        JSONArray res = HttpUtil.get(Globalvar.baseUrl + "/api/courses/" + id + "/resources")
                .asJson().getBody().getArray();
        for (int i = 0; i < res.length(); i++) {
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/source-item.fxml"));
            Parent root = fxmlLoader.load();
            SourceItemController SIC = fxmlLoader.getController();
            SIC.setItem((String)((JSONObject)res.get(i)).get("type"),(String)((JSONObject)res.get(i)).get("fileName"),(Integer)((JSONObject)res.get(i)).get("resourceId"));
            int finalI = i;
            SIC.delete.setOnMouseClicked(e->{
                HttpResponse<JsonNode> response = HttpUtil.delete(Globalvar.baseUrl + "/api/resources/"+(Integer)((JSONObject)res.get(finalI)).get("resourceId"))
                        .header("Content-Type", "application/json")
                        .asJson();
                int statusCode = response.getStatus();
                System.out.println(statusCode);
                if(statusCode == 200){
                    sourceContainer.getChildren().remove(root);
                }
            });
//            switch ((String)((JSONObject)res.get(i)).get("type")){
//                case "DOCUMENT":
//                    docArr.put(root);
//                    break;
//                case "PPT":
//                    pptArr.put(root);
//                    break;
//                case "VIDEO":
//                    vidArr.put(root);
//                    break;
//            }
//            sortMap.put("DOCUMENT",docArr);
//            sortMap.put("PPT",pptArr);
//            sortMap.put("VIDEO",vidArr);
            sourceContainer.getChildren().add(root);
        }
    }
}
